<?php
/**
 * Created by PhpStorm.
 * FileName: IndexController.php
 * User: Administrator
 * Date: 2018/5/22
 * Time: 14:32
 */

namespace Api\Controller;

use Admin\Model\UserModel;
use Common\Lib\Util\ToolUtil;

class AuthController extends ApiController {

    private $userModel;

    function __construct() {
        parent::__construct();
        $this->userModel = new UserModel();
    }

    //判断用户是否已关注过该公众号
    public function index() {
        if (strcasecmp(ToolUtil::getBrowser(),'WeiXin') !== 0) {
            return $this->callBack(null,true);
        }
        vendor('WeiXinSDK.wechat','','.class.php');
        $options = array(
            'appid' => C('appId'), //填写高级调用功能的app id
            'appsecret' => C('appSecret') //填写高级调用功能的密钥
        );
        $weObj = new \Wechat($options);
        $openid = session('openId');
        $userInfo = $weObj->getUserInfo($openid);
        //用户未关注该公众号
        if ($userInfo['subscribe'] === 0) {
            return $this->callBack(null,false);
        }
        return $this->callBack(null,true);
    }

    //实名认证
    public function identification(){
        $user_id = I('request.user_id');
        $mobile = I('request.mobile');
        $real_name = I('request.real_name');
        $id_card = I('request.id_card');
        if (!$user_id) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }
        if (!$this->isMobile($mobile)) {
            return $this->callBack('无效的手机号码！',$this->ERROR_CODE);
        }
        if (!$real_name) {
            return $this->callBack('真实姓名不能为空！',$this->ERROR_CODE);
        }
        if (!$id_card) {
            return $this->callBack('身份证号不能为空！',$this->ERROR_CODE);
        }
        $content = array('mobile' => $mobile,'realname' => $real_name,'idcard' => $id_card);
        $rs = $this->validate($content);
        if ($rs['status'] !== false) {
            if ($this->updateUser() !== false) {
                return $this->callBack("实名认证成功！",$this->SUCCESS_CODE);
            }
            return $this->callBack('实名认证失败！',$this->ERROR_CODE);
        }
        return $this->callBack($rs['msg'],$this->ERROR_CODE);
    }

    private function updateUser() {
        $user_id = I('user_id');
        $mobile = I('mobile');
        $real_name = I('real_name');
        $id_card = I('id_card');
        $userData = array(
            'real_name' => $real_name,
            'mobile' => $mobile,
            'identity' => $id_card
        );
        $rs = $this->userModel->update($userData,array('id' => $user_id));
        return $rs;
    }

    private function validate($content) {
        $rs = array('status' => false);
        $content['detail'] = 1;
        $content['key'] = '498fde07ff6a22b244873416bf2c32af';
        $url = 'http://v.juhe.cn/telecom/query';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($content));
        curl_setopt($curl, CURLOPT_URL, $url);
        $response = curl_exec($curl);
        curl_close($curl);
        if($response){
            $result = json_decode($response,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明发送成功
                if ($result['result']['res'] == 1) {
                    $rs['status'] = true;
                    $rs['msg'] = '验证成功!';
                } else {
                    $rs['msg'] = sprintf('%s,错误代码：%s',$result['result']['resmsg'],$result['result']['rescode']);
                }
            }else{
                //状态非0，说明失败
                $rs['msg'] = '验证失败('.$error_code.')：'.$result['reason'];
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
            $rs['msg'] = '验证失败，请稍后再试！';
        }
        return $rs;
    }

    /**
     * 验证手机号
     * @param string $mobile
     * @return boolean
     */
    private function isMobile($mobile='') {
        if (!preg_match('/^1[34578]{1}\d{9}$/',$mobile)){
            return false;
        }
        return true;
    }

}